import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import * as crypto from 'crypto-js';
import config from 'src/config/config';

@Injectable()
export class XfOcrService {
    constructor(private readonly httpService: HttpService) {}

    async recTextGenerally(
        image: string,
    ): Promise<{ stringify: () => string; result: { category: string; version: string; pages: any[] }; content: string }> {
        const signature_sha = crypto.HmacSHA256(config.xfOcrSetting.signature_origin, config.xfOcrSetting.APISecret);
        const signature = crypto.enc.Base64.stringify(signature_sha);
        const authorization_origin = `api_key="${config.xfOcrSetting.APIKey}",algorithm="hmac-sha256",headers="host date request-line",signature="${signature}"`;
        const authorization = Buffer.from(authorization_origin).toString('base64');
        const url = config.xfOcrSetting.url;
        return new Promise((resolve, reject) => {
            this.httpService
                .post(
                    url,
                    {
                        header: {
                            app_id: config.xfOcrSetting.APPID,
                            status: 3,
                        },
                        parameter: {
                            sf8e6aca1: {
                                category: 'ch_en_public_cloud',
                                result: {
                                    encoding: 'utf8',
                                    compress: 'raw',
                                    format: 'json',
                                },
                            },
                        },
                        payload: {
                            sf8e6aca1_data_1: {
                                encoding: 'jpg',
                                status: 3,
                                image,
                            },
                        },
                    },
                    {
                        params: {
                            authorization,
                            host: config.xfOcrSetting.host,
                            date: config.xfOcrSetting.date,
                        },
                    },
                )
                .toPromise()
                .then((res) => {
                    // interface Result {
                    //     pages: {
                    //         lines: {
                    //             coord: { x: number; y: number }[];
                    //             exception: number;
                    //             words: { content: string; conf: number; coord: { x: number; y: number }[] }[];
                    //         }[];
                    //     }[];
                    // }
                    const text = res.data.payload.result.text;
                    const result = JSON.parse(Buffer.from(text, 'base64').toString());
                    const content = result.pages[0].lines.reduce(
                        (pre, item) => `${pre}${item.words && item.words.length ? item.words[0].content : ''}`,
                        '',
                    );
                    resolve({
                        result,
                        content,
                        stringify() {
                            return JSON.stringify(result);
                        },
                    });
                })
                .catch((err) => {
                    reject(err);
                });
        });
    }
}
